package com.example.smartg;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Response;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.stick.AbsStickPackageHelper;
import tp.xmaihh.serialport.utils.ByteUtil;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.smartg.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class QuJianActivity extends AppCompatActivity implements View.OnClickListener {

    public List<String> auth_str;
    public int[] edit_ids;
    public int[] num_ids;
    String currentGe = "";
    String order = "";
    // 串口配置
    public SerialHelper serialHelper;
    public String SPORT_NAME = "/dev/ttyS4"; //串口路径
    //    public static String SPORT_NAME = "/dev/ttyUSB2"; //串口路径
    public int BAUD_RATE = 19200; //波特率
    public String error_msg;


    //加上计时器
    private Timer mTimer; // 计时器，每2秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        SpUtils.putLong(this,"lastActionTime",System.currentTimeMillis());
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 串口配置/接收返回的数据
     * （在哪调用这函数都行，只需放在打开串口之前就行了）
     */
    public void initSerialConfig() {
        //初始化SerialHelper对象，设定串口名称和波特率
        serialHelper = new SerialHelper(SPORT_NAME, BAUD_RATE) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                Message message = mHandlerQ.obtainMessage();
                message.obj = paramComBean;
                mHandlerQ.sendMessage(message);
            }
        };
        Log.e("Qujian","initSerialConfig");
        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper.setStickPackageHelper(new AbsStickPackageHelper() {
            @Override
            public byte[] execute(InputStream is) {
                try {
                    int available = is.available();
                    if (available > 0) {
                        byte[] buffer = new byte[available];
                        int size = is.read(buffer);
                        if (size > 0) {
                            return buffer;
                        }
                    } else {
                        SystemClock.sleep(50);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }


    //接收到的数据
    public Handler mHandlerQ = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            ComBean comBean = (ComBean) msg.obj;
            //获取数据
            String str = ByteUtil.ByteArrToHex(comBean.bRec);
            System.out.println(str);
            // 把电磁锁反馈返回服务器
//            send_feedback_to_server(str);
            // 根据反馈弹出提示框
            return false;
        }
    });

    //打开串口（先配置，再打开串口）
    public boolean openSerialHelper() {
        //已经打开串口了就不用再打开
        if (serialHelper.isOpen()) {
            Log.e("串口状态", "打开");
            return false;
        }
        //打开串口
        try {
            serialHelper.open();
            Log.e("串口状态", "打开");
        } catch (IOException e) {
            Log.e("串口状态", "关闭");
            e.printStackTrace();
        }

        return true;
    }

    //关闭串口（注销时候或手动关闭）
    public boolean closeSerialHelper() {
        if (!serialHelper.isOpen()) return false;
        serialHelper.close();
        Log.e("qujian","serialHelper.close()");
        return true;
    }


    private void open(String cmd_hex) {
        serialHelper.sendHex(cmd_hex); //十六进制数
    }

    // 发取件码
    public void check_auth_str(String auth_str) {
        String url = "http://10.2.47.115/smartg_api/pickup_manage/get_unpacking_command";
        //实例化
        HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("cabinet_id", "YS001");
            json.put("pickup_code", auth_str);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("exception", e.toString());
//                ToastUtil.error(null, "HTTP FAIL!");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        JSONObject data = jsonObject.optJSONObject("data");
                        JSONArray material_info = data.getJSONArray("material_info");
                        JSONArray cmds = data.optJSONArray("unpacking_command");
                        for (int i = 0; i < cmds.length(); i++) {
                            String cmd = cmds.optString(i);
                            open(cmd);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(1000);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.success(QuJianActivity.this, "开门成功！");
                                }
                            });
                            SpUtils.clear(QuJianActivity.this);
                            stopTimer();
                            finish();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("error", msg);
                        show_error_msg(msg);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void send_feedback_to_server(String feedback) {
        if (feedback.startsWith("8A")) {
            //开门成功
            if (feedback.length() == 20) {
                if (feedback.substring(16, 18).equals("00")) {
                    switch_feedback("YS001", feedback);
                } else {
                    ToastUtil.error(QuJianActivity.this, "开门失败");
                }
            } else if (feedback.length() == 10) {
                if (feedback.substring(6, 8).equals("00")) {
                    switch_feedback("YS001", feedback);
                } else {
                    ToastUtil.error(QuJianActivity.this, "开门失败");
                }
            }
        }
    }

    // 取件码开箱反馈
    public void switch_feedback(String cabinet_id, String unpacking_command) {
        String url = "http://10.2.47.115/smartg_api/pickup_manage/open_box";
        //实例化
        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("cabinet_id", cabinet_id);
            json.put("unpacking_command", unpacking_command);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.e("exception", e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(QuJianActivity.this, "服务器异常-1");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        ToastUtil.success(QuJianActivity.this, "开门成功！");
                        SpUtils.clear(QuJianActivity.this);
                        finish();
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                while (auth_str.size() > 0) {
//                                    int index = auth_str.size() - 1;
//                                    auth_str.remove(index);
//                                    EditText editText = (EditText) findViewById(edit_ids[index]);
//                                    editText.setText("");
//                                }
//                                ToastUtil.success(QuJianActivity.this, "开门成功！");
//                            }
//                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.error(QuJianActivity.this, msg);
                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void show_error_msg(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.error(QuJianActivity.this, msg);
            }
        });
    }

    public void show_success_msg(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                while (auth_str.size() > 0) {
                    int index = auth_str.size() - 1;
                    auth_str.remove(index);
                    EditText editText = (EditText) findViewById(edit_ids[index]);
                    editText.setText("");
                }
                ToastUtil.success(QuJianActivity.this, msg);
            }
        });
    }

    public void show_result(String feedback) {
        if (feedback.startsWith("8A")) {
            String result = feedback.substring(6, 8);
            if (result.equals("00")) {
                show_success_msg("开门成功");
            } else {
                show_error_msg("开门失败");
            }
        }
        if (feedback.startsWith("81")) {
            String result = feedback.substring(6, 8);
            if (result.equals("11")) {
                show_success_msg("关门成功");
            } else {
                show_error_msg("关门失败");
            }
        }
    }

    @Override
    protected void onPause() {
        Log.e("Qujian","onPause");
        super.onPause();
        closeSerialHelper();
        stopTimer();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qu_jian);
        initSerialConfig();
        openSerialHelper();
        auth_str = new ArrayList<>();
        edit_ids = new int[]{R.id.edit_0, R.id.edit_1, R.id.edit_2, R.id.edit_3, R.id.edit_4, R.id.edit_5};
        num_ids = new int[]{R.id.num_0, R.id.num_1, R.id.num_2, R.id.num_3, R.id.num_4, R.id.num_5, R.id.num_6, R.id.num_7, R.id.num_8, R.id.num_9};
        for (int i = 0; i < num_ids.length; i++) {
            Button button = findViewById(num_ids[i]);
            button.setOnClickListener(this);
        }
        ImageButton delBtn = (ImageButton) findViewById(R.id.num_del);
        delBtn.setOnClickListener(this);
        Button sureBtn = (Button) findViewById(R.id.num_sure);
        sureBtn.setOnClickListener(this);
        ImageButton returnBtn = (ImageButton) findViewById(R.id.return_to_home);
        returnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeSerialHelper();
                finish();
            }
        });
        startTimer();
    }

    @Override
    public void onClick(View v) {
        int target_id = v.getId();
        int num_index = -1;
        for (int i = 0; i < num_ids.length; i++) {
            if (num_ids[i] == target_id) {
                num_index = i;
                break;
            }
        }
        if (target_id == R.id.num_del) {
            if (auth_str.size() > 0) {
                int index = auth_str.size() - 1;
                auth_str.remove(index);
                EditText editText = (EditText) findViewById(edit_ids[index]);
                editText.setText("");
            }
        } else if (target_id == R.id.num_sure) {
            if (auth_str.size() != 6) {
                ToastUtil.error(QuJianActivity.this, "请输入6位取件码!");
            } else {
                check_auth_str(String.join("", auth_str));
            }
        } else if (num_index != -1) {
            if (auth_str.size() < 6) {
                String num = Integer.toString(num_index);
                auth_str.add(num);
                int index = auth_str.size() - 1;
                EditText editText = (EditText) findViewById(edit_ids[index]);
                editText.setText(num);
            }
        }
    }

    @Override
    protected void onDestroy() {
        Log.e("Qujian","onDestroy");
        closeSerialHelper();
        super.onDestroy();
    }


    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            // 1分钟未操作停止计时并退出登录
            TextView tv = (TextView) findViewById(R.id.countdown2);
            long mLastActionTime = SpUtils.getLong(QuJianActivity.this,"lastActionTime",0);
            if((System.currentTimeMillis() - mLastActionTime - 5000) / 1000 > 0){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText( 60 - (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "秒后退出！！");
                    }
                });
            }else{
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("");
                    }
                });
            }
            Log.e("=1=", (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "");
            if (System.currentTimeMillis() - mLastActionTime - 5000 > 1000 * 60 * 1) {
                stopTimer();
                SpUtils.clear(QuJianActivity.this);
                finish();
            }

        }
    }

    public void stopTimer() {
        Log.e("=1=", "主页定时任务关闭");
        mTimer.cancel();
    }

    private void startTimer() {
        Log.e("=1=", "主页定时任务启动");
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        SpUtils.putLong(this,"lastActionTime",System.currentTimeMillis());
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 1000);
        //Log.e(TAG, "登录成功开始计时");

    }
}